import uniRequest from '../request'
import { getStorage, asyncClearStorage } from '../storage.js'
import { getToken } from '../auth.js'
const url = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API
const instance = new uniRequest({
  baseUrl: url,
  timeOut: 6000,
  isLoading: true,
})

//配置请求拦截器
instance.interceptors.request = (config) => {
  const token = getToken()
  if (token) {
    config.header['Authorization'] = token
  }
  return config
}

//配置响应拦截器
instance.interceptors.response = async (response) => {
  const { isSuccess, data } = response
  if (!isSuccess) {
    uni.showToast({
      title: '网路异常请重试',
      icon: 'none',
    })
    return response
  }
  //判断服务器状态码
  switch (data.code) {
    case 200:
      return data
    case 401:
      const res = await uni.showModal({
        content: '鉴权失败，请重新登录！',
        showCancel: false,
      })
      if (res) {
        asyncClearStorage()
        uni.reLaunch({
          url: '/pages/index/index',
        })
      }
      return Promise.reject(response)
    default:
      uni.showToast({
        title: '程序异常，请稍后重试',
        icon: 'none',
      })
      return Promise.reject(response)
  }
}

export default instance
